package com.wang.io;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestFileCopy {

    /**
     * 文件拷贝，FileInputStream 和 FileOutputStream 综合应用
     */
    @Test
    public void test01() {
        String srcFilePath = "e:\\下载.jpg";
        String destFilePath = "e:\\下载2.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        byte[] buf = new byte[1024];  // 缓冲数组
        int readLen = 0;  // 记录每次读取的字节个数

        try {
            fileInputStream = new FileInputStream(srcFilePath);
            fileOutputStream = new FileOutputStream(destFilePath, true);

            while ((readLen = fileInputStream.read(buf)) != -1) {  // 当文件还未读完时
                fileOutputStream.write(buf, 0, readLen);  // 把读取到的字节写入磁盘文件
            }
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
